package com.kye.express.business.jd.after_sale.fragment;

import com.kye.express.business.jd.order_detail.model.JDOrderDetailModel;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.IView;
import com.kye.express.databinding.FragmentJdAfterSaleReturnBinding;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.address.AddressBean;
import com.kye.model.bean.jd.after_sale.JDReturnModesResultBean;
import com.kye.model.bean.jd.after_sale.RequestGoodsReturnModes;
import com.kye.model.bean.jd.order_details.JDGoodsAfterSaleTypeBean;
import com.kye.model.bean.jd.order_details.request.RequestGooodsPreserve;
import com.kye.model.bean.user.User;
import com.kye.model.service.JDService;

import java.util.List;

import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public interface JDAfterSaleReturnModeConstract {

    interface JDAfterSaleReturnModeView extends IView {

        void onUser(User user);

        void onLoading();

        void onLoaded();

        void getReturnModesSuccess(List<JDReturnModesResultBean.ResultBean> result);

        void getReturnModesServerFailed(String msg);

        void getReturnModesNetFailed(String message);

        FragmentJdAfterSaleReturnBinding getBinding();

        JDOrderDetailModel getOrderDetailModel();

        JDGoodsAfterSaleTypeBean getSelectedAfterSaleType();

        String getDescriptions();

        User getUserInfo();

        JDReturnModesResultBean.ResultBean getSelectedReturnMode();

        AddressBean getSelectedProvinceTake();

        AddressBean getSelectedCityTake();

        AddressBean getSelectedCountryTake();

        AddressBean getSelectedTownTake();

        AddressBean getSelectedProvinceReceive();

        AddressBean getSelectedCityReceive();

        AddressBean getSelectedCountryReceive();

        AddressBean getSelectedTownReceive();

        void submitSuccess(OpenApiResult<Object> result);

        void submitServerFailed(String msg);

        void submitNetFailed(String message);
    }

    class JDAfterSaleReturnModePresenter extends BasePresenter<JDAfterSaleReturnModeView> {

        private JDService jdService;

        public JDAfterSaleReturnModePresenter() {
            jdService = RetrofitManager.getInstance().createOpenApiService(JDService.class);
        }

        @Override
        public void bind(JDAfterSaleReturnModeView view) {
            super.bind(view);
            UserSession.getInstance()
                    .getUserForRx()
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            getView().onUser(user);
                        }
                    });
        }

        public void getReturnModes(JDOrderDetailModel orderDetailModel, User userInfo) {
            Single.just(new RequestGoodsReturnModes())
                    .doOnSuccess(new Consumer<RequestGoodsReturnModes>() {
                        @Override
                        public void accept(RequestGoodsReturnModes requestGoodsReturnModes) throws Exception {
                            requestGoodsReturnModes.setJdOrderId(Long.parseLong(orderDetailModel.getOrderCode()));
                            requestGoodsReturnModes.setPhone(userInfo.getPhone());
                            requestGoodsReturnModes.setSkuId(Integer.parseInt(orderDetailModel.getSkuId()));
                        }
                    })
                    .flatMap(new Function<RequestGoodsReturnModes, SingleSource<OpenApiResult<JDReturnModesResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<JDReturnModesResultBean>> apply(RequestGoodsReturnModes requestGoodsReturnModes) throws Exception {
                            return jdService.getGoodsReturnModes(requestGoodsReturnModes)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<JDReturnModesResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onLoaded() {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<JDReturnModesResultBean> result, JDReturnModesResultBean jdReturnModesResultBean) {
                            getView().getReturnModesSuccess(jdReturnModesResultBean.getResult());
                        }

                        @Override
                        public void onApiError(OpenApiResult<JDReturnModesResultBean> result, int code, String msg) {
                            getView().getReturnModesServerFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().getReturnModesNetFailed(e.getMessage());
                        }
                    });
        }

        public void submit() {
            Single.just(new RequestGooodsPreserve())
                    .doOnSuccess(new Consumer<RequestGooodsPreserve>() {
                        @Override
                        public void accept(RequestGooodsPreserve requestGooodsPreserve) throws Exception {
                            User userInfo = getView().getUserInfo();
                            JDOrderDetailModel orderDetailModel = getView().getOrderDetailModel();
                            JDGoodsAfterSaleTypeBean selectedAfterSaleType = getView().getSelectedAfterSaleType();
                            JDReturnModesResultBean.ResultBean selectedReturnMode = getView().getSelectedReturnMode();

                            requestGooodsPreserve.setPhone(userInfo.getPhone());
                            requestGooodsPreserve.setJdOrderId(Long.parseLong(orderDetailModel.getOrderCode()));
                            requestGooodsPreserve.setCustomerExpect(Integer.parseInt(selectedAfterSaleType.getCode()));
                            requestGooodsPreserve.setProductProblem(getView().getDescriptions());

                            RequestGooodsPreserve.AsCustomerDtoBean asCustomerDtoBean = new RequestGooodsPreserve.AsCustomerDtoBean();
                            asCustomerDtoBean.setContactPeople(orderDetailModel.getName());
                            asCustomerDtoBean.setTelephone(orderDetailModel.getMobile());
                            asCustomerDtoBean.setMobilePhone(userInfo.getPhone());
                            requestGooodsPreserve.setAsCustomerDto(asCustomerDtoBean);

                            String code = selectedReturnMode.getCode();
                            if ("4".equals(code)) {
                                RequestGooodsPreserve.SenderdateBean senderdateBean = new RequestGooodsPreserve.SenderdateBean();
                                senderdateBean.setSenderType(Integer.parseInt(selectedReturnMode.getCode()));
                                senderdateBean.setSenderProvince(getView().getSelectedProvinceTake().getId());
                                senderdateBean.setSenderCity(getView().getSelectedCityTake().getId());
                                senderdateBean.setSenderCounty(getView().getSelectedCountryTake().getId());
                                AddressBean selectedTownTake = getView().getSelectedTownTake();
                                if (selectedTownTake != null) {
                                    senderdateBean.setSenderVillage(selectedTownTake.getId());
                                }
                                senderdateBean.setSenderAddress(getView().getBinding().takeAddress.getText().toString());
                                requestGooodsPreserve.setSenderdate(senderdateBean);
                            }

                            // 服务类型码，退货(10)、换货(20)、维修(30)
                            RequestGooodsPreserve.ReturngoodsBean returngoodsBean = new RequestGooodsPreserve.ReturngoodsBean();
//                            returngoodsBean.setReturnType(getView().); // 返件方式，自营配送(10),第三方配送(20);换、修这两种情况必填（默认值）
                            returngoodsBean.setReturnProvince(getView().getSelectedProvinceReceive().getId());
                            returngoodsBean.setReturnCity(getView().getSelectedCityReceive().getId());
                            returngoodsBean.setReturnCounty(getView().getSelectedCountryReceive().getId());
                            AddressBean selectedTownReceive = getView().getSelectedTownReceive();
                            if (selectedTownReceive != null) {
                                returngoodsBean.setReturnVillage(selectedTownReceive.getId());
                            }
                            requestGooodsPreserve.setReturngoods(returngoodsBean);

                            RequestGooodsPreserve.DetailedBean detailedBean = new RequestGooodsPreserve.DetailedBean();
                            detailedBean.setSkuId(Integer.parseInt(orderDetailModel.getSkuId()));
                            detailedBean.setGoodsNumber(1);
                            requestGooodsPreserve.setDetailed(detailedBean);
                        }
                    })
                    .flatMap(new Function<RequestGooodsPreserve, SingleSource<OpenApiResult<Object>>>() {
                        @Override
                        public SingleSource<OpenApiResult<Object>> apply(RequestGooodsPreserve requestGooodsPreserve) throws Exception {
                            return jdService.applyGooodsPreserve(requestGooodsPreserve)
                                    .compose(getView().bindToLifecycleDestroy());

                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<Object>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<Object> result, Object o) {
                            getView().submitSuccess(result);
                        }

                        @Override
                        public void onApiError(OpenApiResult<Object> result, int code, String msg) {
                            getView().submitServerFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().submitNetFailed(e.getMessage());
                        }
                    });
        }
    }
}
